import { ESStaticMesh } from 'earthsdk3';
import { ESUeViewer, UeESSceneObject } from 'earthsdk3-ue';
import { bind, track } from "earthsdk3";
import { ESFeTreeAdding } from '.';
import { switchMeshPath } from '../ESForest/switchMeshPath';

export class UeESFeTreeAdding<T extends ESFeTreeAdding = ESFeTreeAdding> extends UeESSceneObject<T> {
    static readonly type = this.register<ESFeTreeAdding, ESUeViewer>('ESUeViewer', ESFeTreeAdding.type, this);
    static combinationClass = true;

    private _eSStaticMesh = this.dv(new ESStaticMesh(`${this.sceneObject.id}_ESStaticMesh`));
    get eSStaticMesh() { return this._eSStaticMesh; }

    constructor(sceneObject: T, ueViewer: ESUeViewer) {
        super(sceneObject, ueViewer);

        const viewer = ueViewer.viewer;
        if (!viewer) {
            console.warn(`viewer is undefined!`);
            return;
        }
        const eSStaticMesh = this.eSStaticMesh;
        sceneObject.mainClass = eSStaticMesh;
        ueViewer.add(eSStaticMesh);
        this.dispose(() => ueViewer.delete(eSStaticMesh))
        //属性同步
        {
            this.d(bind([eSStaticMesh, 'scale'], [sceneObject, 'scale']));
            this.d(bind([eSStaticMesh, 'position'], [sceneObject, 'position']));
            this.d(bind([eSStaticMesh, 'rotation'], [sceneObject, 'rotation']));
        }
        {
            const updateMeshPath = () => {
                eSStaticMesh.mesh = switchMeshPath(typeof sceneObject.url == 'string' ? sceneObject.url : sceneObject.url?.url);
            }
            updateMeshPath();
            this.d(sceneObject.urlChanged.don(() => { updateMeshPath() }));
        }
        //显隐控制
        {
            const updateShow = () => {
                this.eSStaticMesh.show = sceneObject.show;
            }
            updateShow();
            this.d(sceneObject.showChanged.don(() => { updateShow() }));
        }
        this.dispose(this.eSStaticMesh.pickedEvent.don(pickedInfo => {
            if (sceneObject.allowPicking ?? false) {
                // @ts-ignore
                sceneObject.pickedEvent.emit(new SceneObjectPickedInfo(sceneObject, pickedInfo));
            }
        }))
    }
}
